<script lang="ts" setup>
import {onMounted, ref, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {useFavorStore} from "../../store/FavorStore.ts";
import FlexBox from "../../components/common/FlexBox.vue";
import {Folder, FolderOpened} from "@element-plus/icons-vue";
import {type FavorFolder, FavorFolderType} from "../../network/types/Favor.ts";
import {toNumber} from "../../utils/Utils.ts";
import {useTopicStore} from "../../store/TopicStore.ts";
import type {TopicInfo, TopicListData} from "../../network/types/Topic.ts";
import TopicTable from "../../components/topic/TopicTable.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {scrollShortKeys, type ShortKey} from "../../utils/ShortKeys.ts";

const loading = ref(false)
const route = useRoute()
const router = useRouter()
const favorStore = useFavorStore();
const topicStore = useTopicStore();
// 当前收藏夹ID
const folderId = ref<number>()
// 当前页
const page = ref<number>()
// 主题列表数据
const data = ref<TopicListData>()
// 选中的主题
const selectedTopics = ref<TopicInfo[]>()
// 查询收藏夹列表
const folderList = (force: boolean = false) => {
  loading.value = true
  page.value = toNumber(route.query.page) || 1
  favorStore.folderList(Number(route.params.userId), undefined, force).then(res => {
    // 当前收藏夹
    folderId.value = toNumber(route.query.folder) || res.find(i => i.defaultFolder)?.id
    loading.value = false
    favorTopic(force)
  }).catch(r => {
    console.error(r)
    loading.value = false
  })
}
// 查询收藏夹下的主题
const favorTopic = (force: boolean = false) => {
  loading.value = true
  topicStore.favorTopic(folderId.value!!, page.value, force).then(res => {
    data.value = res
    console.log(res)
    loading.value = false
  }).catch(r => {
    console.error(r)
    loading.value = false
  })
}
const changePage = (page: number) => {
  router.push({query: {page, folder: route.query.folder}, params: route.params})
}

const refresh = () => folderList(true);

const topicDelete = () => {
  const favorId = selectedTopics.value?.map(i => i.favorId)
  if (!favorId || favorId.length === 0 || !folderId.value) return
  // 弹窗确认是否删除收藏
  ElMessageBox.confirm(`即将删除选中的 ${favorId.length} 个收藏`, '提示', {type: 'warning'}).then(() => {
    favorStore.topicDelete(folderId.value!!, favorId).then(res => {
      ElMessage.success(res)
      refresh();
    }).catch(r => {
      console.error(r)
      ElMessage.error('删除失败')
    })
  })
}

const topicMove = async (folder: FavorFolder) => {
  console.log(folder)
  const topics = selectedTopics.value || []
  if (topics.length === 0) return
  // 弹窗确认是否移动
  ElMessageBox.confirm(`即将移动选中的 ${topics.length} 个收藏到收藏夹 ${folder.name}`, '提示', {type: 'warning'}).then(() => topicMoveBatch(topics, folder.id))
}
// 逐个移动主题到收藏夹
const topicMoveBatch = async (topics: TopicInfo[], toFolder: number) => {
  loading.value = true
  try {
    for (const topic of topics) {
      await favorStore.topicMove(folderId.value!!, toFolder, topic.topicId, topic?.reply?.replyId)
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
    refresh()
  }
}
const rename = (folder: FavorFolder) => {
  ElMessageBox.prompt(`请输入收藏夹名称`, '收藏夹改名', {
    inputValue: folder.name
  }).then(({value}) => {
    favorStore.folderModify(folder.id, value, folder.type === FavorFolderType.PUBLIC).then(res => {
      ElMessage.success(res)
      refresh()
    }).catch(r => {
      console.error(r)
    })
  })
}

const switchPublic = (folder: FavorFolder, isPublic: boolean) => {
  favorStore.folderModify(folder.id, folder.name, isPublic).then(res => {
    ElMessage.success(res)
    refresh()
  }).catch(r => {
    console.error(r)
  })
}


// 快捷键
const shortKeys: ShortKey[] = [
  {title: '刷新', keys: ['alt', 'r'], action: refresh},
  ...scrollShortKeys,
]
onMounted(() => folderList())
watch(route, () => folderList())

</script>

<template>
  <!--快捷键-->
  <div class="short-key-div">
    <template v-for="k in shortKeys">
      <span v-shortkey="k.keys" @shortkey="k.action">{{ k.title }}</span>
    </template>
  </div>
  <div v-loading="loading" class="route-root">
    <div style="display: flex; justify-content: space-between;">
      <!--收藏夹-->
      <div style="text-align: start;margin: 0 8px">
        <flex-box v-for="folder in favorStore.favorFolders" style="margin-right: 5px">
          <el-icon :size="30">
            <FolderOpened v-if="folder.id===folderId"/>
            <Folder v-else/>
          </el-icon>
          <!-- 点击跳转到收藏夹-->
          <router-link :to="{query:{folder:folder.id}}">
            <span>{{ folder.name }}({{ folder.length }})</span>
          </router-link>
          <!-- 类型-->
          <el-button-group size="small">
            <el-button v-if="folder.type===FavorFolderType.DEFAULT" effect="dark" type="success">默认</el-button>
            <el-button v-else-if="folder.type===FavorFolderType.PRIVATE" effect="dark" size="small" type="primary" @click="switchPublic(folder,true)">私有</el-button>
            <el-button v-else-if="folder.type===FavorFolderType.PUBLIC" effect="dark" size="small" type="danger" @click="switchPublic(folder,false)">公开</el-button>
            <el-button size="small" type="info" @click="rename(folder)">改名</el-button>
          </el-button-group>
        </flex-box>
      </div>

      <el-button-group>
        <el-dropdown>
          <el-button type="primary">移动到</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="folder in favorStore.favorFolders" :disabled="folder.id===folderId" @click="topicMove(folder)">
                {{ folder.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="success" @click="refresh">刷新</el-button>
        <el-button type="danger" @click="topicDelete">删除</el-button>
      </el-button-group>
    </div>
    <!--主题列表-->
    <div v-if="data">
      <!-- 翻页器-->
      <el-pagination :current-page="page" :page-size="data.size" :total="data.total"
                     hide-on-single-page
                     layout="prev, pager, next,jumper, total"
                     @current-change="changePage"/>
      <!--主题列表-->
      <topic-table :topics="data.data" selection show-parent @selection-change="selectedTopics=$event"/>
    </div>
  </div>
</template>

<style scoped>

</style>